package org.finalministry.utils;

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.finalministry.database.connection.FinalministryDatabaseConnection;

/**
 * Check if database is initialized with all necessary data and tools for
 * spatial methods and if necessary initialize it
 * 
 * @author admin
 * 
 */
public class DatabaseInitializer {

	public static void initialize(FinalministryDatabaseConnection connection)
			throws ClassNotFoundException, IOException {

		String checkSQL = "SELECT * FROM COUNTRY";
		Statement stmt;

		try {
			stmt = connection.getConnection().createStatement();
			ResultSet result = stmt.executeQuery(checkSQL);
			while (result.next()) {
				// System.out.println(result.getString(1));

			}
			stmt.close();
		} catch (SQLException e) {
			System.out.println("Initializing database ...");
			try {
				forceDatabaseInitialization(connection);
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
		}

	}

	/**
	 * This will force the initialization of all tables
	 * 
	 * @param connection
	 * @throws IOException
	 * @throws SQLException
	 * @throws ClassNotFoundException
	 */
	public static void forceDatabaseInitialization(FinalministryDatabaseConnection connection) throws IOException, SQLException,
			ClassNotFoundException {
		importFileIntoDatabase("sql/initFinalministryDatabase.sql", connection.getConnection());
		importFileIntoDatabase("sql/importCountries.sql", connection.getConnection());
		importFileIntoDatabase("sql/geodb.sql", connection.getConnection());
	}

	public static void forceDatabaseSpatialOnlyInitialization(FinalministryDatabaseConnection connection) throws IOException, SQLException,
			ClassNotFoundException {

		importFileIntoDatabase("sql/geodb.sql", connection.getConnection());
	}

	private static void importFileIntoDatabase(String importFile, Connection connection) throws IOException, SQLException {

		File file = new File(importFile);
		List<String> lines = FileUtils.readLines(file);
		ScriptRunner script = new ScriptRunner(connection, true, false, lines);
		script.runScript();
	}

}
